package 线程;

public class TestThread2改良 {
    public static void main(String[] args) {
            //测试
        Ticket2 t = new Ticket2();
        Thread t1 = new Thread(t);//记住传参！！！
        Thread t2 = new Thread(t);
        Thread t3 = new Thread(t);
        Thread t4 = new Thread(t);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
class Ticket2 implements Runnable{
//
 static    int tickets = 100;
    @Override
    public void run() {
        synchronized (Ticket2.class){
            while (true){//用一个while循环来卖票
                if(tickets>0) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }//Thread.currentThread().getName()获取线程名
                    System.out.println(Thread.currentThread().getName() + "=" + tickets--);
                }if(tickets<=0) break;;
            }
        }
/*出现负票原因：没有if判断ticket>0
Thread-2=-1
Thread-1=-2
 */

    }
}